package com.loan.controller;

import com.alibaba.fastjson.JSONObject;
import com.loan.dto.Result;
import com.loan.entity.*;
import com.loan.repository.*;
import com.loan.service.*;
import com.loan.util.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * Created by huxudong on 17/6/29.
 */
@Controller
@RequestMapping("api/loan")
public class ApiController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private BannerService bannerService;

    @Autowired
    private CategoryChannelService categoryChannelService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ChannelService channelService;

    @Autowired
    private CreditCardService creditCardService;

    @Autowired
    private PersonalCenterRepository personalCenterRepository;

    @Autowired
    private SettingsRepository settingsRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ApplyRepository applyRepository;

    @Autowired
    private NoticeRepository noticeRepository;

    @ResponseBody
    @RequestMapping("home")
    public Result index(@PageableDefault(value = 15, sort = { "id" }, direction = Sort.Direction.DESC) Pageable pageable){
        Result result = new Result();
        result.setCode(200);
        result.setMessage("操作成功");
        JSONObject data = new JSONObject();

        //banner
        List<Banner> banners =  bannerService.findByTagAndFlag(1,0);
        data.put("banners",banners);

        //贷款分类推荐
        List<Category> categorys = categoryService.findByFlag(0);
        data.put("categorys",categorys);

        //热门渠道
        List<Channel> hotChannels = channelService.findByFlagAndIsHot(0,1);
        data.put("hotChannels",hotChannels);

        List<Notice> notices = noticeRepository.findAllByOrderByATimeDesc();
        data.put("notices",notices);

        //优选渠道
//        List<Channel> preferredChannels = channelService.findByFlagAndIsHot(0,2);
//        data.put("preferredChannels",preferredChannels);

        result.setBody(data);
        return result;
    }

    /**
     * 信用卡页面
     * @param pageable
     * @return
     */
    @ResponseBody
    @RequestMapping("credit")
    public Result credit(@PageableDefault(value = 15, sort = { "id" }, direction = Sort.Direction.DESC) Pageable pageable){
        Result result = new Result();
        result.setCode(200);
        result.setMessage("操作成功");
        JSONObject data = new JSONObject();

        //banner
        List<Banner> banners =  bannerService.findByTagAndFlag(2,0);
        data.put("banners",banners);

        //信用卡列表
        List<CreditCard> credits = creditCardService.findByFlag(0);
        data.put("credits",credits);

        result.setBody(data);
        return result;
    }


    @ResponseBody
    @RequestMapping("categorys")
    public List<Category> categorys(){
        return categoryService.findByFlag(0);
    }


    @ResponseBody
    @RequestMapping("channel/{categoryId}")
    public Result categorys(@PathVariable Long categoryId){
        Result result = new Result();
        result.setCode(200);
        result.setMessage("操作成功");
        List<CategoryChannel> ccs =  categoryChannelService.findByCategoryId(categoryId);
        List<Channel> channels = new ArrayList<Channel>();
        for(CategoryChannel cc : ccs){
            channels.add(cc.getChannel());
        }
        Collections.sort(channels,channels.get(0));
        JSONObject body = new JSONObject();
        body.put("channels",channels);
        result.setBody(body);
        return result;
    }


    @ResponseBody
    @RequestMapping("personal/center")
    public Result personalCenter(){
        Result result = new Result();
        result.setCode(200);
        result.setMessage("操作成功");
        final List<PersonalCenter> list = personalCenterRepository.findByFlagOrderBySort(0);
        JSONObject data = new JSONObject();
        data.put("centers",list);
        result.setBody(data);
        return result;
    }

    @ResponseBody
    @RequestMapping("settings/strategy")
    public Result getStrategy(int version){
        Result result = new Result();
        result.setCode(200);
        result.setMessage("操作成功");
        List<Settings> list = settingsRepository.findByType(1);
        JSONObject data = new JSONObject();
        if(list != null && list.size() > 0){
            int dbversion =  list.get(0).getStatus();
            System.out.println(version);
            System.out.println(dbversion);
            if(version == dbversion){
                data.put("status",1);
            }else{
                data.put("status",0);
            }
        }else{
            data.put("status",0);
        }
        result.setBody(data);
        return result;
    }

    @ResponseBody
    @RequestMapping("user/reg")
    public Result reg(String mobile , String password , String name){
        Result result = new Result();
        result.setCode(200);
        result.setMessage("操作成功");
        User dbuser = userRepository.findByPhone(mobile);
        if(dbuser != null){
            result.setCode(1002);
            result.setMessage("手机号已经存在");
            return result;
        }
        User user = new User();
        user.setName(name);
        user.setPhone(mobile);
        user.setPassword(password);
        String token = MD5Util.md5(name+"_"+mobile+new Date().getTime());
        user.setToken(token);
        userRepository.saveAndFlush(user);
        result.setBody(user);
        return result;
    }


    @ResponseBody
    @RequestMapping("user/login")
    public Result login(String mobile , String password){
        Result result = new Result();
        result.setCode(200);
        result.setMessage("登录成功");
        JSONObject data = new JSONObject();
        User user = userRepository.findByPhoneAndPasswordAndFlag(mobile,password,0);
        if(user == null){
            result.setCode(1001);
            result.setMessage("手机号或密码错误");
            return result;
        }
        data.put("name",user.getName());
        data.put("token",user.getToken());
        result.setBody(data);
        return result;
    }

    @ResponseBody
    @RequestMapping("apply")
    public Result apply(Apply apply){
        Result result = new Result();
        result.setCode(200);
        result.setMessage("保存成功");
        apply.setaTime(new Date());
        apply.setFlag(0);
        applyRepository.save(apply);
        return result;
    }


    @ResponseBody
    @RequestMapping("notices")
    public Result notices(){
        List<Notice> notices = noticeRepository.findAllByOrderByATimeDesc();
        Result result = new Result();
        result.setCode(200);
        result.setMessage("保存成功");
        result.setBody(notices);
        return result;
    }

}
